package com.zhong.system.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhong.common.constant.Constants;
import com.zhong.common.constant.UserConstants;
import com.zhong.common.core.domain.TreeSelect;
import com.zhong.common.core.domain.entity.SysMenu;
import com.zhong.common.core.domain.entity.SysRole;
import com.zhong.common.core.domain.entity.SysUser;
import com.zhong.common.utils.SecurityUtils;
import com.zhong.common.utils.StringUtils;
import com.zhong.common.utils.WrapperUtils;
import com.zhong.system.domain.SysRoleMenu;
import com.zhong.system.domain.SysUserRole;
import com.zhong.system.domain.vo.MetaVo;
import com.zhong.system.domain.vo.RouterVo;
import com.zhong.system.mapper.SysMenuMapper;
import com.zhong.system.mapper.SysRoleMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜单 业务层处理
 *
 * @author zhongzc
 */
@Service
@RequiredArgsConstructor
public class SysMenuService extends ServiceImpl<SysMenuMapper, SysMenu>
{
    public static final String PREMISSION_STRING = "perms[\"{0}\"]";

    private final SysRoleMapper roleMapper;

    private final SysRoleMenuService roleMenuService;

    private final SysUserRoleService userRoleService;

    private final SysRoleService roleService;

    /**
     * 根据用户查询系统菜单列表
     *
     * @param userId 用户ID
     * @return 菜单列表
     */
    public List<SysMenu> selectMenuList(String userId)
    {
        return selectMenuList(new SysMenu(), userId);
    }

    public List<SysMenu> findListByIdList(List<String> idList){
        return list(Wrappers.<SysMenu>lambdaQuery().in(SysMenu::getId,idList).eq(SysMenu::getStatus,"0").orderByAsc(SysMenu::getOrderNum));
    }

    /**
     * 查询系统菜单列表
     *
     * @param menu 菜单信息
     * @return 菜单列表
     */
    public List<SysMenu> selectMenuList(SysMenu menu, String userId)
    {
        List<SysMenu> menuList = null;
        // 管理员显示所有菜单信息
        if (SysUser.isAdmin(userId))
        {
            menuList = list(WrapperUtils.getLambdaQueryWrapper(menu).orderByAsc(SysMenu::getOrderNum));
        }
        else
        {
            //获取用户角色映射
            List<SysUserRole> urList = userRoleService.findListByUserId(userId);
            if(!urList.isEmpty()){
                //判断角色是否启用
                List<SysRole> roleList = roleService.findListByIdList(urList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList()));
                if(!roleList.isEmpty()){
                    //获取角色菜单映射
                    List<SysRoleMenu> rmList = roleMenuService.findListByRoleIdList(roleList.stream().map(SysRole::getId).collect(Collectors.toList()));
                    //获取菜单列表
                    if(!rmList.isEmpty()){
                        menuList = list(WrapperUtils.getLambdaQueryWrapper(menu).in(SysMenu::getId,rmList.stream()
                                .map(SysRoleMenu::getMenuId).collect(Collectors.toList())).eq(SysMenu::getStatus,"0").orderByAsc(SysMenu::getOrderNum));
                    }
                }
            }
        }

        return menuList==null ? Collections.EMPTY_LIST : menuList;
    }

    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户名称
     * @return 菜单列表
     */
    public List<SysMenu> selectMenuTreeByUserId(String userId)
    {
        List<SysMenu> menus = null;
        String[] types = {"M","C"};
        if (SecurityUtils.isAdmin(userId))
        {
            menus = list(Wrappers.<SysMenu>lambdaQuery().in(SysMenu::getMenuType,Arrays.asList(types)).eq(SysMenu::getStatus,"0").orderByAsc(SysMenu::getOrderNum));
        }
        else
        {
            List<SysUserRole> urList = userRoleService.findListByUserId(userId);
            if(!urList.isEmpty())
            {
                List<SysRole> roleList = roleService.findListByIdList(urList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList()));
                if(!roleList.isEmpty()){
                    List<SysRoleMenu> rmList = roleMenuService.findListByRoleIdList(roleList.stream().map(SysRole::getId).collect(Collectors.toList()));
                    if(!rmList.isEmpty()){
                        List<String> menuIdList = rmList.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
                        menus = list(Wrappers.<SysMenu>lambdaQuery()
                                .in(SysMenu::getId,menuIdList)
                                .in(SysMenu::getMenuType,Arrays.asList(types))
                                .eq(SysMenu::getStatus,"0")
                                .orderByAsc(SysMenu::getOrderNum));
                    }
                }
            }
        }

        if(menus==null){
            menus = Collections.EMPTY_LIST;
        }
        return getChildPerms(menus, "0");
    }

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    public List<RouterVo> buildMenus(List<SysMenu> menus)
    {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (SysMenu menu : menus)
        {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
            List<SysMenu> cMenus = menu.getChildren();
            if (StringUtils.isNotEmpty(cMenus) && UserConstants.TYPE_DIR.equals(menu.getMenuType()))
            {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            }
            else if (isMenuFrame(menu))
            {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            else if ("0".equals(menu.getParentId()) && isInnerLink(menu))
            {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    public List<SysMenu> buildMenuTree(List<SysMenu> menus)
    {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        List<String> tempList = menus.stream().map(SysMenu::getId).collect(Collectors.toList());
        for (Iterator<SysMenu> iterator = menus.iterator(); iterator.hasNext();)
        {
            SysMenu menu = (SysMenu) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId()))
            {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param menus 菜单列表
     * @return 下拉树结构列表
     */
    public List<TreeSelect> buildMenuTreeSelect(List<SysMenu> menus)
    {
        List<SysMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean checkMenuNameUnique(SysMenu menu)
    {
        SysMenu info = getOne(Wrappers.<SysMenu>lambdaQuery().eq(SysMenu::getParentId,menu.getParentId()).eq(SysMenu::getMenuName,menu.getMenuName()),false);
        if (StringUtils.isNotNull(info) && !info.getId().equals(menu.getId()))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenu menu)
    {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu))
        {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu)
    {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (!"0".equals(menu.getParentId()) && isInnerLink(menu))
        {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if ("0".equals(menu.getParentId()) && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame()))
        {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu))
        {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenu menu)
    {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu))
        {
            component = menu.getComponent();
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && "0".equals(menu.getParentId()) && isInnerLink(menu))
        {
            component = UserConstants.INNER_LINK;
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu))
        {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenu menu)
    {
        return "0".equals(menu.getParentId()) && UserConstants.TYPE_MENU.equals(menu.getMenuType()) && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenu menu)
    {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) && StringUtils.ishttp(menu.getPath());
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenu menu)
    {
        return !"0".equals(menu.getParentId()) && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, String parentId)
    {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext();)
        {
            SysMenu t = (SysMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (parentId.equals(t.getParentId()))
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t 子节点
     */
    private void recursionFn(List<SysMenu> list, SysMenu t)
    {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t)
    {
        List<SysMenu> tlist = new ArrayList<SysMenu>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext())
        {
            SysMenu n = (SysMenu) it.next();
            if (n.getParentId().equals(t.getId()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t)
    {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    public String innerLinkReplaceEach(String path)
    {
        return StringUtils.replaceEach(path, new String[] { Constants.HTTP, Constants.HTTPS, Constants.WWW, "." }, new String[] { "", "", "", "/" });
    }

    /**
     * 保存菜单
     * @param menu  菜单对象
     * @return
     */
    @Transactional
    public boolean saveMenu(SysMenu menu)
    {
        SysMenu parent = getById(menu.getParentId());
        if(parent==null){
            menu.setAncestors("0");
        }else {
            menu.setAncestors(parent.getAncestors()+","+parent.getId());
        }
        return save(menu);
    }

    /**
     * 更新菜单
     * @param menu  菜单对象
     */
    @Transactional
    public boolean updateMenu(SysMenu menu)
    {
        SysMenu oldMenu = getById(menu.getId());
        if(!oldMenu.getParentId().equals(menu.getParentId()))
        {
           String oldAncestors =  oldMenu.getAncestors()+","+oldMenu.getId();
           String newAncestors =  null;
           SysMenu parent = getById(menu.getParentId());
           if(parent!=null){
               newAncestors = parent.getAncestors()+","+parent.getId();
           }else {
               newAncestors = "0";
           }
           menu.setAncestors(newAncestors);
           newAncestors = newAncestors +","+ menu.getId();
           update(Wrappers.<SysMenu>lambdaUpdate().likeRight(SysMenu::getAncestors,oldAncestors).set(SysMenu::getAncestors,newAncestors));
        }
        return updateById(menu);
    }

    /**
     * 删除菜单管理信息
     *
     * @param id 菜单ID
     * @return 结果
     */
    @Transactional
    public boolean deleteMenuById(String id)
    {
        SysMenu menu = getById(id);
        remove(Wrappers.<SysMenu>lambdaQuery().likeRight(SysMenu::getStatus,menu.getAncestors()+","+menu.getId()));
        //删除权限-待实现
        return removeById(id);
    }
}
